package test.long_polling.controller;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.Collection;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : example
 * @ Author: XuLeHuang
 * @ Date: 2022/7/23 16:43
 * @ Description:
 */
@Controller
@RequestMapping("/polling")
public class PollingController {

    private static final Long TIME_OUT = 10000l;
    // 存放监听某个Id的长轮询集合
    // 线程同步结构
    public static Multimap<String, DeferredResult<String>> watchRequests = Multimaps.synchronizedMultimap(HashMultimap.create());

    /**
     *
     * 设置监听
     */
    @GetMapping(path = "watch/{id}")
    @ResponseBody
    public DeferredResult<String> watch(@PathVariable String id) {
        // 延迟对象设置超时时间
        DeferredResult<String> deferredResult = new DeferredResult<>(TIME_OUT);
        // 异步请求完成时移除 key，防止内存溢出
        deferredResult.onCompletion(() -> {
            watchRequests.remove(id, deferredResult);
        });
        // 注册长轮询请求
        watchRequests.put(id, deferredResult);
        return deferredResult;
    }

    /**
     *
     * 变更数据
     */
    @GetMapping(path = "publish/{id}")
    @ResponseBody
    public String publish(@PathVariable String id) {
        // 数据变更 取出监听ID的所有长轮询请求(多个浏览器，单个浏览器不同窗口只认为一个，每次publish只响改变一个)，并一一响应处理
        if (watchRequests.containsKey(id)) {
            Collection<DeferredResult<String>> deferredResults = watchRequests.get(id);
            System.out.println(deferredResults.size());
            for (DeferredResult<String> deferredResult : deferredResults) {
                //只要set，就认为改变了
                deferredResult.setResult("我更新了" + new Date());
            }
        }
        return "success";
    }
    //当请求超过设置的超时时间，会抛出AsyncRequestTimeoutException异常，这里直接用@ControllerAdvice全局捕获统一返回即可，前端获取约定好的状态码后再次发起长轮询请求，如此往复调用。

    @ControllerAdvice
    public class AsyncRequestTimeoutHandler {

        @ResponseStatus(HttpStatus.NOT_MODIFIED)
        @ResponseBody
        @ExceptionHandler(AsyncRequestTimeoutException.class)
        public String asyncRequestTimeoutHandler(AsyncRequestTimeoutException e) {
            System.out.println("异步请求超时");
            return "304";
        }
    }
}